<script setup lang="ts">
import Table from '@/components/table/index.vue';
import useGetList from '@/hooks/useGetList';
import { getShipDataRecord, uploadShipData, GetShipDataRecordParams, ShipDataRecord } from '@/services/data';
import { ElButton, ElMessage, UploadFile, UploadFiles } from 'element-plus';
import { UploadFilled } from '@element-plus/icons-vue';

interface Props {
  visible: boolean;
  active: boolean;
}

interface Emits {
  (e: "update:visible", visible: boolean): void;
}

const getListFC = async (params: GetShipDataRecordParams) => {
  try {
    const res = await getShipDataRecord(params);
    const { page, length } = params;
    return {
      list: (res.list || []).map((record, idx) => ({
        ...record,
        index: idx + 1 + (page - 1) * length,
      })),
      total: res.total || 0,
      page: params.page || 1,
      size: params.length || 15,
    };
  } catch {
    return {
      list: [],
      total: 0,
      page: 1,
      size: 15,
    };
  }
};

const props = defineProps<Props>();
const emits = defineEmits<Emits>();
const {
  list,
  getList,
  loading,
  total,
  page,
  size,
} = useGetList(getListFC);
const dbFiles = ref<UploadFiles>([]);
const uploadLoading = ref(false);
const selectRecords = ref<ShipDataRecord[]>([]);

const show = computed({
  get() {
    return props.visible;
  },
  set(visible: boolean) {
    emits("update:visible", visible);
  },
});

const columns = [
  {
    type: 'selection',
    label: '',
    align: 'center',
    width: 80,
  },
  {
    prop: 'dbname',
    label: '文件名称',
    align: 'center',
  },
  {
    prop: 'created_time',
    label: '入库时间',
    align: 'center',
  },
  {
    prop: 'count',
    label: '数据量（条）',
    align: 'center',
    width: 130,
  },
  {
    prop: 'type',
    label: '舰船类型',
    align: 'center',
    width: 120,
  },
  {
    prop: 'depart',
    label: '时间跨度',
    align: 'center',
    render: (columnsProps: { row: ShipDataRecord }) => {
      const { stime, etime } = columnsProps.row;
      return h('div', null, [
        h('div', null, stime),
        h('div', null, etime),
      ]);
    },
  },
  {
    prop: 'comment',
    label: '训练状态',
    align: 'center',
    render: (columnsProps: { row: ShipDataRecord }) => {
      const status = columnsProps.row.status;
      const statusText = ['未训练', '训练中', '已训练'];
      return h('span', null, statusText[status]);
    },
  },
];

const handleSelectionChange = (select: any) => {
  selectRecords.value = select;
};

const handleQuery = (page: number, length: number) => {
  getList({ page, length });
};

const handleDbFileUpload = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  // console.log(uploadFiles, uploadFiles.map(file => {
  //   return URL.createObjectURL(file.raw!);
  // }));
  dbFiles.value = uploadFiles;
};

const handleUploadShipData = async () => {
  if (dbFiles.value.length === 0) {
    ElMessage({
      type: 'warning',
      message: '请选择要导入的文件',
    });
    return;
  }
  uploadLoading.value = true;
  try {
    const formData = new FormData();
    dbFiles.value.forEach(file => {
      formData.append('dbname', file.raw as any as File);
    })
    await uploadShipData(formData);
    ElMessage({
      type: 'success',
      message: '数据导入成功',
    });
    show.value = false;
    handleQuery(1, size.value);
  } catch {
    ElMessage({
      type: 'warning',
      message: '数据导入失败，请重试',
    });
  } finally {
    uploadLoading.value = false;
  }
};

const handleCancelUpload = () => {
  show.value = false;
  dbFiles.value = [];
};

const getSelectedRecords = () => {
  return selectRecords.value.map((record) => record.id);
};

onMounted(() => {
  handleQuery(1, size.value);
});

defineExpose({
  getSelectedRecords,
});
</script>

<template>
  <Table
    v-if="props.active"
    :loading="loading"
    :list="list"
    border
    height="calc(100vh - 35px - 62px - 50px - 40px - 60px)"
    :columns="columns"
    :total="total"
    :page-no="page"
    :page-size="size"
    :get-list="(pageNo: number, pageSize: number) => handleQuery(pageNo, pageSize)"
    :handle-selection-change="handleSelectionChange"
  />
  <ElDialog
    class="custom-dialog ship-db-upload-dialog"
    v-model="show"
    title="综合导航数据导入"
    width="400"
    align-center
    @close="() => handleCancelUpload()"
    append-to-body
  >
    <ElUpload
      class="ship-db-upload"
      drag
      multiple
      show-file-list
      :auto-upload="false"
      :file-list="dbFiles"
      accept=".db"
      @change="handleDbFileUpload"
    >
      <ElIcon class="el-icon--upload"><UploadFilled /></ElIcon>
      <div class="el-upload__text">
        <em>拖入或点选DB文件上传</em>
      </div>
    </ElUpload>
    <div class="dialog-footer" style="padding-left: 0;">
      <ElButton class="custom-btn" @click="() => handleCancelUpload()">取消</ElButton>
      <ElButton type="primary" :loading="uploadLoading" @click="() => handleUploadShipData()">确定</ElButton>
    </div>
  </ElDialog>
</template>

<style lang="less" scoped>
</style>
